package com.wthink.hzgj.service

import android.util.Log
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.wthink.hzgj.busInfo.BusInfo
import com.wthink.hzgj.data.BusRepository
import com.wthink.hzgj.data.domain.*
import com.wthink.hzgj.data.repository.DefaultBusRepository
import com.wthink.hzgj.wireless.Wireless
import com.wthink.newMain.data.*
import com.wthink.newMain.settings.config.inner.netconfig.adapter.NetConfig
import com.wthink.newMain.settings.config.inner.netconfig.adapter.NetConfigInfo


data class ActRet(val success: Boolean, val err: String? = null)

object MessageHelp {

    val busRepository: BusRepository = DefaultBusRepository()

    fun parseGps(payload: String): Location {
        val obj = JSON.parseObject(payload)
        return Location(obj.getDouble("lat"), obj.getDouble("lon"), obj.getDouble("speed").toInt())
    }

    fun parseDevState(payload: String): DevState {
        val obj = JSON.parseObject(payload)
        val gps = obj.getIntValue("gps")
        val net = obj.getIntValue("net")
        val pl = obj.getIntValue("pl")

        return DevState(net == 0, pl == 0, gps == 0)
    }

    suspend fun parseBusState(payload: String): BusStateA {
        val obj = JSON.parseObject(payload)
        val lineId = obj.getString("line")
        val upDir = "0".equals(obj.getString("dir"))
        val stationId = obj.getString("station")

        //1到站 2离站
        val state = obj.getString("state")
        val lineName = busRepository.findLineNameById(lineId) ?: ""
        val stationName = busRepository.findStationNameById(stationId) ?: ""
        return BusStateA(lineId, lineName, stationId, stationName, upDir,state)
    }

    fun parseLineStation(payload: String): LineStation {
        val obj = JSON.parseObject(payload)
        val lineId = obj.getString("line")
        val lineName = obj.getString("name")

        val up = obj.getJSONArray("up").map {
            val item = it as JSONObject
            Station(0, item.getString("station"), item.getString("name"), lineId, true)
        }

        val down = obj.getJSONArray("down").map {
            val item = it as JSONObject
            Station(0, item.getString("station"), item.getString("name"), lineId, false)
        }
        return LineStation(lineId, lineName, up, down)
    }

    fun parseLineList(payload: String): List<Line> {
        return JSON.parseObject(payload).getJSONArray("id").map {
            Line(0, it as String, "")
        }
    }

    fun parseAppverInfo(payload: String): AppverInfo {
        val obj = JSON.parseObject(payload)
        val ver = obj.getIntValue("ver")
        val size = obj.getLong("size")
        val sig = obj.getString("sig")
        val busVer = obj.getString("bus_ver")
        Log.d("versionMsg", sig + "->" + ver + "->" + size + "->" + busVer)
        return AppverInfo(ver, sig, size, busVer)
    }

    fun parseCameraInfo(payload: String): CameraInfo {
        val rsp = JSON.parseObject(payload)
        val cameraList = rsp.getJSONArray("camera").map { it.toString() }

        val videoList = rsp.getJSONArray("video").map {
            val item = it as JSONObject
            item.getString("camera")
        }.toList()

        return CameraInfo(cameraList, videoList)
    }

    fun parseCameraList(payload: String): CameraFileInfo {
        val obj = JSON.parseObject(payload)
        val jsonArray = obj.getJSONArray("list")
        if (jsonArray != null) {
            val fileList = jsonArray.map {
                val item = it as JSONObject
                val path = item.getString("name")
                val size = "" + (item.getIntValue("size") / 1024 / 1024) + "M"
                val isDir = item.getString("isDir")
                val flag = isDir.equals("dir")
                val split = path.split("/")
                val name = split.get(split.size - 1)
                FileDetail(path, size, flag, name)
            }.toList()
            return CameraFileInfo(fileList)
        } else {
            return CameraFileInfo(emptyList())
        }
    }

    fun parseServiceVoiceList(payload: String): ServiceVoiceInfo {
        val obj = JSON.parseObject(payload)
        val jsonArray = obj.getJSONArray("list")
        if (jsonArray != null) {
            val serviceVoiceList = jsonArray.map {
                val item = it as JSONObject
                val key = item.getIntValue("key")
                val content = item.getString("content")
                ServiceVoiceDetail(key, content)
            }.toList()
            return ServiceVoiceInfo(serviceVoiceList)
        } else {
            return ServiceVoiceInfo(emptyList())
        }
    }

    fun parseVideoList(payload: String): List<String> {
        val rsp = JSON.parseObject(payload)
        return rsp.getJSONArray("camera").map {
            val item = it as JSONObject
            item.getString("camera")
        }.toList()
    }

    fun parse808(payload: String): Bus808 {
        val obj = JSON.parseObject(payload)

        return Bus808(obj.getString("type"), obj.getString("payload"))
    }

    fun parseFile(payload: String): String {
        val obj = JSON.parseObject(payload)

        return obj.getString("content")
    }

    fun parseActRet(payload: String): ActRet {
        val obj = JSON.parseObject(payload)
        val success = obj.getBoolean("success")
        val err = if (success) {
            null
        } else {
            obj.getString("err")
        }
        return ActRet(success, err)
    }

    fun parseTime(payload: String): Long {
        val obj = JSON.parseObject(payload)
        return obj.getLong("date")
    }

    fun parseGetVol(payload: String): DeviceVol {
        val obj = JSON.parseObject(payload)
        val in_vol = obj.getString("in_vol").toInt()
        val out_vol = obj.getString("out_vol").toInt()
        val mic_vol = obj.getString("mic_vol").toInt()
        return DeviceVol(in_vol, out_vol, mic_vol)
    }

    fun parseBusConfig(payload: String): BusConfig {
        val obj = JSON.parseObject(payload)
        val type = obj.getString("type")
        val car_num = obj.getString("car_num")
        val car_color = obj.getString("car_color")
        return BusConfig(type, car_num, car_color)
    }


    fun parseLogin(payload: String): Login {
        val obj = JSON.parseObject(payload)
        val success = obj.getString("success")
        val err = obj.getString("err")
        return Login(success, err)
    }

    fun parseGpsInfo(payload: String): GpsInfo {
        val obj = JSON.parseObject(payload)
        val lat = obj.getString("lat")
        val latd = obj.getString("latd")
        val lon = obj.getString("lon")
        val lond = obj.getString("lond")
        val time = obj.getString("time")
        val ts = obj.getString("ts")
        val status = obj.getString("status")
        val elv = obj.getString("elv")
        val count = obj.getString("count")
        val visate = obj.getString("visate")
        val signal = obj.getString("signal")
        val speed = obj.getString("speed")
        val cog = obj.getString("cog")
        val mode = obj.getString("mode")
        val ant = obj.getString("ant")
        return GpsInfo(
            lat,
            latd,
            lon,
            lond,
            time,
            ts,
            status,
            elv,
            count,
            visate,
            signal,
            speed,
            cog,
            mode,
            ant
        )
    }

    fun parseStorage(payload: String): Storage {
        val obj = JSON.parseObject(payload)
        val udisk_total = obj.getString("udisk_total")
        val udisk_free = obj.getString("udisk_free")
        val hdisk_total = obj.getString("hdisk_total")
        val hdisk_free = obj.getString("hdisk_free")
        return Storage(udisk_total, udisk_free, hdisk_total, hdisk_free)
    }

    fun parseDevStatus(payload: String): Boolean {
        val obj = JSON.parseObject(payload)
        val state = obj.getIntValue("state")
        return state == 0
    }


    fun parseWireless(payload: String): Wireless {
        val obj = JSON.parseObject(payload)
        val attached = obj.getString("attached")
        val sim1 = obj.getString("sim1")
        val sim2 = obj.getString("sim2")
        val net_state = obj.getString("net_state")
        val net_type = obj.getString("net_type")
        val ip = obj.getString("ip")
        val operator = obj.getString("operator")
        val signal = obj.getString("signal")
        val imsi = obj.getString("imsi")
        val iccid = obj.getString("iccid")
        return Wireless(
            attached,
            sim1,
            sim2,
            net_state,
            net_type,
            ip,
            operator,
            signal,
            imsi,
            iccid
        )
    }

    fun parseBusInfo(payload: String): BusInfo {
        val obj = JSON.parseObject(payload)
        val vdr_model = obj.getString("vdr_model")
        val vdr_vendorid = obj.getString("vdr_vendorid")
        val vid = obj.getString("vid")
        val simno = obj.getString("simno")
        val car_num = obj.getString("car_num")
        val car_color = obj.getString("car_color")
        val city_id = obj.getString("city_id")
        val car_vin = obj.getString("car_vin")
        val province_id = obj.getString("province_id")
        return BusInfo(
            vdr_model,
            vdr_vendorid,
            vid,
            simno,
            car_num,
            car_color,
            city_id,
            car_vin,
            province_id)
    }
    fun parseBasicInfo(payload: String): BasicInfo {
        val obj = JSON.parseObject(payload)
        val vdr_model = obj.getString("vdr_model")
        val vdr_vendorid = obj.getString("vdr_vendorid")
        val vid = obj.getString("vid")
        val simno = obj.getString("simno")
        val car_num = obj.getString("car_num")
        val car_color = obj.getString("car_color")
        val city_id = obj.getString("city_id")
        val car_vin = obj.getString("car_vin")
        val province_id = obj.getString("province_id")
        val sn = obj.getString("sn")
        val dev_id = obj.getString("dev_id")
        val car_id = obj.getString("car_id")
        val driver_id = obj.getString("driver_id")
        val driver_name = obj.getString("driver_name")
        val line_id = obj.getString("line_id")

        return BasicInfo(
            vdr_model,
            vdr_vendorid,
            vid,
            simno,
            car_num,
            car_color,
            city_id,
            car_vin,
            province_id
            , sn, dev_id, car_id, line_id, driver_id, driver_name
        )
    }

    fun parseNetconfig(payload: String): NetConfigInfo {
        val obj = JSON.parseObject(payload)
        val netConfigList = obj.getJSONArray("list").map {
            val item = it as JSONObject
/*            val type = NetconfigUtil.parseType(item.getIntValue("type"))
            val ip = item.getString("ip")
            val uport =  item.getIntValue("uport")
            val tport = item.getIntValue("tport")
            val vendor = NetconfigUtil.parseVendor(item.getIntValue("vendor"))
            val status = NetconfigUtil.parseStatus(item.getIntValue("status"))
            val protocol = NetconfigUtil.parseProtocol(item.getIntValue("protocol"))
            val platform_type = NetconfigUtil.parsePlatform_type(item.getIntValue("platform_type"))*/
            val type = item.getString("type")
            val ip = item.getString("ip")
            val tport = item.getIntValue("tport")
            val uport = item.getIntValue("uport")
            val vendor = item.getString("vendor")
            val status = item.getString("status")
            val protocol = item.getString("protocol")
            val platform_type = item.getString("platform_type")
            val deleteFlag = false
            NetConfig(
                type,
                ip,
                tport,
                uport,
                vendor,
                status,
                protocol,
                platform_type,
                deleteFlag
            )
        }.toList()
        return NetConfigInfo(netConfigList)
    }

    fun parseDevVersion(payload: String):VersionInfos {
        val obj = JSON.parseObject(payload)
        val mpu_version = obj.getString("mpu_version")
        val vpu_version = obj.getString("vpu_version")
        val dsm_adas_version = obj.getString("dsm_adas_version")

        return VersionInfos(mpu_version,vpu_version,dsm_adas_version)
    }

    fun parseUser(payload: String): UsersInfo {
        val obj = JSON.parseObject(payload)
        val userList = obj.getJSONArray("users").map {
            val item = it as JSONObject
            val type = item.getIntValue("type")
            val name = item.getString("name")
            User(
                type,
                name
            )
        }.toList()
        return UsersInfo(userList)
    }

    fun parseSerialList(payload: String):SerialInfo{
        val rsp = JSON.parseObject(payload)
        val baudRateList = rsp.getJSONArray("baudrate").map { it.toString() }
        val serialList = rsp.getJSONArray("serial").map {
            val item = it as JSONObject
            val name = item.getString("name")
            val baudrate = item.getString("baudrate")
            SerialData(name,baudrate)
        }.toList()

        return SerialInfo(baudRateList, serialList)
    }

    fun parseCanList(payload: String):SerialInfo{
        val rsp = JSON.parseObject(payload)
        val baudRateList = rsp.getJSONArray("baudrate").map { it.toString() }
        val serialList = rsp.getJSONArray("CAN").map {
            val item = it as JSONObject
            val name = item.getString("name")
            val baudrate = item.getString("baudrate")
            SerialData(name,baudrate)
        }.toList()
        return SerialInfo(baudRateList, serialList)
    }

    fun parseFireConfig(payload: String):FireData{
        val rsp = JSON.parseObject(payload)
        val type_list = rsp.getJSONArray("type_list").map { it.toString() }
        val back_light_time_list = rsp.getJSONArray("back_light_time_list").map { it.toString() }
        val type = rsp.getString("type")
        val delay_time = rsp.getString("delay_time")
        val start_time = rsp.getString("start_time")
        val end_time = rsp.getString("end_time")
        val back_light_time = rsp.getString("back_light_time")
        return FireData(type_list, type, delay_time, start_time, end_time, back_light_time, back_light_time_list)
    }

    fun parseCameraConfig(payload: String):CameraSettingsData{
        val rsp = JSON.parseObject(payload)
        val cameraList = rsp.getJSONArray("camera").map { it.toString() }
        return CameraSettingsData(cameraList)
    }

    fun parseAutoTimingConfig(payload: String):AutoTimingData{
        val rsp = JSON.parseObject(payload)
        val host_list = rsp.getJSONArray("host_list").map { it.toString() }
        val gps = rsp.getString("gps")
        val ntp = rsp.getString("ntp")
        val host = rsp.getString("host")
        val server = rsp.getString("server")
        return AutoTimingData(gps, ntp, host, server, host_list)
    }

    fun parseStationGps(payload: String):LoadStationData{
        val rsp = JSON.parseObject(payload)
        val valid = rsp.getString("valid")
        val current_lat = rsp.getString("current_lat")
        val current_lon = rsp.getString("current_lon")
        val speed = rsp.getString("speed")
        val current_direction = rsp.getString("current_direction")
        val station_lat = rsp.getString("station_lat")
        val station_lon = rsp.getString("station_lon")
        val station_direction = rsp.getString("station_direction")
        return LoadStationData(valid, current_lat, current_lon, speed, current_direction, station_lat, station_lon, station_direction)
    }
}